<template>
    <el-button plain type="primary" style="margin-bottom: 10px;" @click="Open()">添加</el-button>
    <el-table :data="tableData" border style="width: 100%">
        <el-table-column fixed type="index" label="序号" width="60" />
        <el-table-column prop="materialGroupCode" label="物料群组编号" width="180" />
        <el-table-column prop="materialGroupName" label="物料群组名称" width="180" />
        <el-table-column prop="warehouseName" label="仓库名称" width="150" />
        <el-table-column prop="currentInventory" label="当前库存" width="150" />
        <el-table-column prop="inventoryCap" label="库存上限" width="150" />
        <el-table-column prop="inventoryFloor" label="库存下限" width="150" />
        
        <el-table-column fixed="right" label="操作" min-width="120">
            <template v-slot="scope">
                  <el-button link type="success" @click="Out(scope.row)">出库</el-button>
                <el-button link type="success" @click="In(scope.row)">入库</el-button>
                <el-button link type="warning" @click="OpenUpdate(scope.row)">编辑</el-button>
                <el-button link type="danger" @click="Del(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 添加群组库存弹窗 -->
    <el-dialog v-model="dialogVisible" title="添加群组库存" width="500px">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
            <el-form-item label="库存上限" prop="inventoryCap">
                <el-input v-model="ruleForm.inventoryCap" placeholder="请输入库存上限" />
            </el-form-item>
            <el-form-item label="库存下限" prop="inventoryFloor">
                <el-input v-model="ruleForm.inventoryFloor" placeholder="请输入库存下限" />
            </el-form-item>
            <el-form-item label="当前库存" prop="currentInventory">
                <el-input v-model="ruleForm.currentInventory" placeholder="请输入当前库存" />
            </el-form-item>
            <el-form-item label="所属仓库" prop="warehouseId">
                <el-select v-model="ruleForm.warehouseId" placeholder="请选择仓库">
                    <el-option v-for="item in warehouseData" :label="item.warehouseName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料群组" prop="materialGroupId">
                <el-select v-model="ruleForm.materialGroupId" placeholder="请选择物料群组">
                    <el-option v-for="item in materialGroupData" :label="item.materialGroupName" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    
    <!-- 修改群组库存弹窗 -->
    <el-dialog v-model="dialogVisibleUpdate" title="修改群组库存" width="500px">
        <el-form ref="ruleFormRef" :model="ruleFormUpdate" :rules="rules" label-width="120px">
            <el-form-item label="库存上限" prop="inventoryCap">
                <el-input v-model="ruleFormUpdate.inventoryCap" placeholder="请输入库存上限" />
            </el-form-item>
            <el-form-item label="库存下限" prop="inventoryFloor">
                <el-input v-model="ruleFormUpdate.inventoryFloor" placeholder="请输入库存下限" />
            </el-form-item>
            <el-form-item label="当前库存" prop="currentInventory">
                <el-input v-model="ruleFormUpdate.currentInventory" placeholder="请输入当前库存" />
            </el-form-item>
            <el-form-item label="所属仓库" prop="warehouseId">
                <el-select v-model="ruleFormUpdate.warehouseId" placeholder="请选择仓库">
                    <el-option v-for="item in warehouseData" :label="item.warehouseName" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="所属物料群组" prop="materialGroupId">
                <el-select v-model="ruleFormUpdate.materialGroupId" placeholder="请选择物料群组">
                    <el-option v-for="item in materialGroupData" :label="item.materialGroupName" :value="item.id" />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisibleUpdate = false">取消</el-button>
                <el-button type="primary" @click="submitFormUpdate(ruleFormRef)">确定</el-button>
            </span>
        </template>
    </el-dialog>
    
    <!-- 出库弹窗 -->
    <el-dialog v-model="dialogVisibleOut" title="群组物料出库" width="500px">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleFormOut" :rules="rulesOut" label-width="auto">
            <el-form-item label="出库编号" prop="outInCode">
                <div style="display: flex; gap: 10px;">
                    <el-input v-model="ruleFormOut.outInCode" :disabled="isOutCodeGenerated" />
                    <el-button type="primary" @click="generateOutCode" :disabled="isOutCodeGenerated">
                        {{ isOutCodeGenerated ? '已生成' : '生成编号' }}
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="出库数量" prop="outInCount">
                <div class="inventory-control">
                    <el-button class="inventory-btn" @click="decreaseOutCount">-</el-button>
                    <el-input v-model="ruleFormOut.outInCount" class="inventory-input" />
                    <el-button class="inventory-btn" @click="increaseOutCount">+</el-button>
                </div>
            </el-form-item>
            <el-form-item style="padding-left: 400px;">
                <el-tag type="success">出库</el-tag>
            </el-form-item>
            <el-form-item>
                <el-button @click="dialogVisibleOut = false">取消</el-button>
                <el-button type="primary" @click="submitFormOut(ruleFormRef)">确定出库</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
    
    <!-- 入库弹窗 -->
    <el-dialog v-model="dialogVisibleIn" title="群组物料入库" width="500px">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleFormIn" :rules="rulesIn" label-width="auto">
            <el-form-item label="入库编号" prop="outInCode">
                <div style="display: flex; gap: 10px;">
                    <el-input v-model="ruleFormIn.outInCode" :disabled="isInCodeGenerated" />
                    <el-button type="primary" @click="generateInCode" :disabled="isInCodeGenerated">
                        {{ isInCodeGenerated ? '已生成' : '生成编号' }}
                    </el-button>
                </div>
            </el-form-item>
            <el-form-item label="入库数量" prop="outInCount">
                <div class="inventory-control">
                    <el-button class="inventory-btn" @click="decreaseInCount">-</el-button>
                    <el-input v-model="ruleFormIn.outInCount" class="inventory-input" />
                    <el-button class="inventory-btn" @click="increaseInCount">+</el-button>
                </div>
            </el-form-item>
            <el-form-item style="padding-left: 400px;">
                <el-tag type="success">入库</el-tag>
            </el-form-item>
            <el-form-item>
                <el-button @click="dialogVisibleIn = false">取消</el-button>
                <el-button type="primary" @click="submitFormIn(ruleFormRef)">确定入库</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>

    <!--分页-->
    <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize" :page-sizes="[3, 5, 10, 20]"
        :background="true" layout="total, sizes, prev, pager, next, jumper" :total="page.totalcount" />
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useCounterStore } from '@/stores/counter'

// 获取Pinia状态
const pinia = useCounterStore();

// 表格数据
const tableData = ref([])

// 分页参数
const page = reactive({
    pageIndex: 1,
    pageSize: 3,
    totalcount: 0
})
const pagee = reactive({
  Index: 1,
  Size: 100,
  totalcount: 0
})
// 仓库数据
const warehouseData = ref([{
    "id":null,
    "warehouseName":''
}])

// 物料群组数据
const materialGroupData = ref([{
     "id":null,
    "materialGroupName":''
}])

// 监听分页参数变化
watch(page, () => {
    getGroupInventory();
})

// 生命周期钩子
onMounted(() => {
    // 初始化数据
    getGroupInventory()
    getWarehouse()
    getMaterialGroup()
})

// 获取群组库存数据
const getGroupInventory = () => {
    // 调用API获取群组库存数据
    axios.get('/api/ProductionModules/GetGroupInventory', { params: page }).then(res => {
        if (res.data.code == 200) {
            tableData.value = res.data.totalPage
            page.totalcount = res.data.totalcount
        }
    })
}

// 获取仓库数据
//仓库显示
const getWarehouse=()=>{
  axios.get('/api/ProductionModules/GetWare', { params: pagee }).then(res => {
    if (res.data.code == 200) {
      warehouseData.value = res.data.data.totalPage
      pagee.totalcount = res.data.data.totalcount
    }
  })
}

// 获取物料群组数据
const getMaterialGroup = () => {
    axios.get('/api/MaterialManagement/GetMaterialGroup', { 
        params: { PageIndex: 1, PageSize: 100 } 
    }).then(res => {
        if (res.data.code == 200) {
            materialGroupData.value = res.data.totalPage
        }
    })
}

// 控制添加弹窗显示
const dialogVisible = ref(false);
const Open = () => {
    dialogVisible.value = true;
    // 重置表单
    ruleForm.warehouseId = ""
    ruleForm.currentInventory = ""
    ruleForm.inventoryCap = ""
    ruleForm.inventoryFloor = ""
    ruleForm.materialGroupId = ""
    ruleForm.createrPeople = pinia.piniaDto?.realName || ""
}

// 表单引用
const ruleFormRef = ref<FormInstance>()

// 添加表单数据
const ruleForm = reactive({
    "warehouseId": "",
    "currentInventory": "",
    "inventoryCap": "",
    "inventoryFloor": "",
    "materialGroupId": "",
    "createrPeople": ""
})

// 表单验证规则
const rules = reactive<FormRules>({
    warehouseId: [
        { required: true, message: '请选择仓库', trigger: 'change' },
    ],
    currentInventory: [
        { required: true, message: '请输入当前库存', trigger: 'blur' },
    ],
    inventoryCap: [
        { required: true, message: '请输入库存上限', trigger: 'blur' },
    ],
    inventoryFloor: [
        { required: true, message: '请输入库存下限', trigger: 'blur' },
    ],
    materialGroupId: [
        { required: true, message: '请选择物料群组', trigger: 'change' },
    ],
    createrPeople: [
        { required: true, message: '请输入创建人', trigger: 'blur' },
    ],
})

// 提交添加表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送添加请求
            axios.post('/api/ProductionModules/AddGroupInventory', ruleForm).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisible.value = false;
                    getGroupInventory(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 控制修改弹窗显示
const dialogVisibleUpdate = ref(false);
const OpenUpdate = (row: any) => {
    dialogVisibleUpdate.value = true
    // 填充表单数据
    ruleFormUpdate.id = row.id
    ruleFormUpdate.warehouseId = row.warehouseId
    ruleFormUpdate.currentInventory = row.currentInventory
    ruleFormUpdate.inventoryCap = row.inventoryCap
    ruleFormUpdate.inventoryFloor = row.inventoryFloor
    ruleFormUpdate.materialGroupId = row.materialGroupId
}

// 修改表单数据
const ruleFormUpdate = reactive({
    "id": "",
    "warehouseId": "",
    "currentInventory": "",
    "inventoryCap": "",
    "inventoryFloor": "",
    "materialGroupId": "",
})

// 提交修改表单
const submitFormUpdate = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送修改请求
            axios.put('/api/ProductionModules/UpdateGroupInventory', ruleFormUpdate).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleUpdate.value = false;
                    getGroupInventory(); // 提交成功后刷新表格数据
                } else {
                    ElMessage.error(res.data.message)
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 删除群组库存
const Del = (row: any) => {
    ElMessageBox.confirm(
        '确定要删除该群组库存吗？删除后数据将无法恢复。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 发送删除请求
            axios({
                url: "/api/ProductionModules/DeleteGroupInventory",
                method: 'post',
                data: row
            })
                .then(res => {
                    if (res.data.code == 200) {
                        ElMessage.success(res.data.message);
                        getGroupInventory(); // 删除成功后刷新表格数据
                    } else {
                        ElMessage.error(res.data.message);
                    }
                }).catch(error => {
                    ElMessage.error('删除失败，请重试');
                    console.error('Delete error:', error);
                });
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
}

// 控制出库入库弹窗显示
const dialogVisibleOut = ref(false)
const dialogVisibleIn = ref(false)

// 控制编号生成状态
const isOutCodeGenerated = ref(false)
const isInCodeGenerated = ref(false)

// 打开出库弹窗
const Out = (row: any) => {
    dialogVisibleOut.value = true
    ruleFormOut.materialGroupId = row.materialGroupId
    ruleFormOut.outInCount = 0 // 初始化出库数量为0
    ruleFormOut.outInCode = "" // 重置出库编号
    isOutCodeGenerated.value = false // 重置生成状态
}

// 打开入库弹窗
const In = (row: any) => {
    dialogVisibleIn.value = true
    ruleFormIn.materialGroupId = row.materialGroupId
    ruleFormIn.outInCount = 0 // 初始化入库数量为0
    ruleFormIn.outInCode = "" // 重置入库编号
    isInCodeGenerated.value = false // 重置生成状态
}

// 出库表单数据
const ruleFormOut = reactive({
    "outInCode": "", // 出库编号
    "outIn": 1, // 1表示出库
    "outInCount": 0, // 出库数量
    "materialGroupId": null, // 物料群组ID
    "createrPeople": pinia.piniaDto?.realName || "" // 创建人
})

// 入库表单数据
const ruleFormIn = reactive({
    "outInCode": "", // 入库编号
    "outIn": 2, // 2表示入库
    "outInCount": 0, // 入库数量
    "materialGroupId": null, // 物料群组ID
    "createrPeople": pinia.piniaDto?.realName || "" // 创建人
})

// 出库表单验证规则
const rulesOut = reactive<FormRules>({
    outInCode: [
        { required: true, message: '请输入出库编号', trigger: 'blur' },
    ],
    outInCount: [
        {
            required: true,
            message: '请输入出库数量',
            trigger: 'change',
        },
    ]
})

// 入库表单验证规则
const rulesIn = reactive<FormRules>({
    outInCode: [
        { required: true, message: '请输入入库编号', trigger: 'blur' },
    ],
    outInCount: [
        {
            required: true,
            message: '请输入入库数量',
            trigger: 'change',
        },
    ]
})

// 提交出库表单
const submitFormOut = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送出库请求
            axios.post('/api/ProductionModules/AddGroupOut', ruleFormOut).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleOut.value = false
                    getGroupInventory(); // 刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 提交入库表单
const submitFormIn = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 发送入库请求
            axios.post('/api/ProductionModules/AddGroupIn', ruleFormIn).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    dialogVisibleIn.value = false
                    getGroupInventory(); // 刷新表格数据
                } else {
                    ElMessage.error(res.data.message);
                }
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 增加出库数量（点击加号添加1000）
const increaseOutCount = () => {
    if (!ruleFormOut.outInCount) {
        ruleFormOut.outInCount = 1000;
    } else {
        ruleFormOut.outInCount = Number(ruleFormOut.outInCount) + 1000;
    }
}

// 减少出库数量
const decreaseOutCount = () => {
    if (!ruleFormOut.outInCount || Number(ruleFormOut.outInCount) < 1000) {
        ElMessage.warning('出库数量不能小于0');
        return;
    }
    ruleFormOut.outInCount = Number(ruleFormOut.outInCount) - 1000;
}

// 增加入库数量（点击加号添加1000）
const increaseInCount = () => {
    if (!ruleFormIn.outInCount) {
        ruleFormIn.outInCount = 1000;
    } else {
        ruleFormIn.outInCount = Number(ruleFormIn.outInCount) + 1000;
    }
}

// 减少入库数量
const decreaseInCount = () => {
    if (!ruleFormIn.outInCount || Number(ruleFormIn.outInCount) < 1000) {
        ElMessage.warning('入库数量不能小于0');
        return;
    }
    ruleFormIn.outInCount = Number(ruleFormIn.outInCount) - 1000;
}

// 生成6位随机数
const generateRandomNumber = () => {
    return Math.floor(100000 + Math.random() * 900000).toString();
}

// 生成出库编号
const generateOutCode = () => {
    ruleFormOut.outInCode = 'CK' + generateRandomNumber();
    isOutCodeGenerated.value = true;
    ElMessage.success('出库编号已生成');
}

// 生成入库编号
const generateInCode = () => {
    ruleFormIn.outInCode = 'RK' + generateRandomNumber();
    isInCodeGenerated.value = true;
    ElMessage.success('入库编号已生成');
}
</script>

<style scoped>
/* 分页容器样式 */
.el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
}

/* 表单样式 */
.el-form {
    max-width: 100%;
}

/* 弹窗底部按钮样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

/* 出入库数量控制区域样式 */
.inventory-control {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
}

.inventory-btn {
    flex: 0 0 auto;
    padding: 8px 12px;
    font-size: 16px;
    font-weight: bold;
}

.inventory-input {
    flex: 1;
    margin: 0 10px;
    text-align: center;
}

.inventory-input :deep(.el-input__inner) {
    text-align: center;
}
</style>
